/* Copyright 2012 Dustin Mitchell <dmmitche [at] gmail [dot] com>
 *
 * Licensed under the GPLv3.  See included LICENSE.txt for full details.
 */

#include <stdlib.h>
#include <stdio.h>

#include "gps_sensor.h"
#include "log.h"



static int gps_sensor_read (union sensor *s, union sensor_reading *r)
{
  char buff[128];
  ssize_t nread;

  if (!s || !r || s->sensor.type != SENSOR_GPS) {
    log (LOG_ERR, "invalid param");
    return -1;
  }

  r->type = SENSOR_GPS;

  nread = uart_read (&s->gps.hw_uart, buff, 128);
  buff[nread - 1] = '\0';

  return 1;
}

static int gps_sensor_get_selectable (union sensor *s)
{
  if (!s || s->sensor.type != SENSOR_GPS) {
    log (LOG_ERR, "invalid param");
    return -1;
  }

  if (s->sensor.type != SENSOR_GPS) {
    log (LOG_ERR, "sensor is not a GPS sensor");
    return -1;
  }

  return uart_get_fd (&s->gps.hw_uart);
}

static struct sensor_ops gps_sensor_ops = {
  .read = gps_sensor_read,
  .get_selectable = gps_sensor_get_selectable
};



int gps_sensor_create (struct gps_sensor *gps, struct uart_hw_module *hw_uart,
                       int baud)
{
  if (!gps || !hw_uart) {
    log (LOG_ERR, "invalid param");
    return -1;
  }

  if (sensor_base_create (&gps->base, SENSOR_GPS, &gps_sensor_ops) == -1) {
    log (LOG_ERR, "unable to create sensor_base");
    return -1;
  }

  if (uart_create (&gps->hw_uart, hw_uart, baud) == -1) {
    log (LOG_ERR, "unable to create uart");
    return -1;
  }

  return 0;
}

void gps_sensor_destroy (struct gps_sensor *gps)
{
  if (!gps) {
    log (LOG_ERR, "invalid param");
    return;
  }

  uart_destroy (&gps->hw_uart);
}

struct uart * gps_sensor_get_uart (struct gps_sensor *gps)
{
  if (!gps) {
    log (LOG_ERR, "invalid param");
    return NULL;
  }

  return &gps->hw_uart;
}
